package dao

import (
	"context"
	"strconv"
	"strings"
	"system-admin/internal/dal"
	"system-admin/internal/models"
)

type AlarmNotifyRecord struct {
	models.AlarmNotifyRecord
	AlarmTypeName    string `json:"alarm_type_name"`
	ReceiveUserNames string `json:"receive_user_names"`
	NotifyTypeName   string `json:"notify_type_name"`
	ProvinceID       string `json:"province_id" gorm:"column:province_id"`
	CityID           string `json:"city_id" gorm:"column:city_id"`
	DistrictID       string `json:"district_id" gorm:"column:district_id"`
	LocationID       string `json:"location_id" gorm:"column:location_id"`
}

// List 通知记录列表
func (AlarmNotifyRecord) List(
	ctx context.Context,
	query *dal.Query,
	merchantPath string, // 商户路径
	alarmType string, // 告警类型
	robotID string, // 设备id
	receiveUser string, // 接收用户
	startTime, endTime int64, // 开始时间，结束时间
	provinceID, cityID, districtId, locationID string, //省市区位置筛选
	page, limit int,
	notRepeated bool, // 是否去重，正常不同的通知人都会显示出来
) (records []*AlarmNotifyRecord, total int64, err error) {
	al := query.AlarmNotifyRecord.As("al")
	td := query.TempDevice.As("td")
	//  告警通知记录过滤条件
	alTx := al.WithContext(ctx).Where(al.CreatedAt.Between(startTime, endTime))
	{
		// 设备id
		if robotID != "" {
			alTx = alTx.Where(al.RobotID.Eq(robotID))
		}
		// 告警类型
		if alarmType != "" {
			alarmTypes := []int{}
			for _, val := range strings.Split(alarmType, ",") {
				valInt, _ := strconv.Atoi(val)
				alarmTypes = append(alarmTypes, valInt)
			}
			alTx = alTx.Where(al.AlarmType.In(alarmTypes...))
		}
		// 接收用户
		if receiveUser != "" {
			alTx = alTx.Where(al.ReceiveUsers.Like("%" + receiveUser + "%"))
		}
	}
	// 告警记录和临时设备表联表
	alTx = alTx.Join(td, al.RobotID.EqCol(td.RobotID))
	// 设备临时表过滤
	// 商户路径条件
	alTx = alTx.Where(td.MerchantPath.Like(merchantPath + "%"))
	// group查询条件
	// 省份条件
	areaGroup := td.WithContext(ctx)
	{
		if provinceID != "" {
			areaGroup = areaGroup.Or(td.ProvinceID.In(strings.Split(provinceID, ",")...))
		}
		// 城市条件
		if cityID != "" {
			areaGroup = areaGroup.Or(td.CityID.In(strings.Split(cityID, ",")...))
		}
		// 区县条件
		if districtId != "" {
			areaGroup = areaGroup.Or(td.DistrictID.In(strings.Split(districtId, ",")...))
		}
		// 位置条件
		if locationID != "" {
			areaGroup = areaGroup.Or(td.LocationID.In(strings.Split(locationID, ",")...))
		}
	}
	// 加上group条件
	alTx = alTx.Where(areaGroup)
	if notRepeated {
		alTx.Where(al.ReceiveUsers.Eq("1"))
	}
	total, _ = alTx.Count()
	// 字段
	alTx.Select(
		al.ID,
		al.RobotID,
		al.AlarmType,
		al.ReceiveUsers,
		al.NotifyType,
		al.CreatedAt,
		al.PushResult,
		td.ProvinceID,
		td.CityID,
		td.DistrictID,
		td.LocationID,
	)
	// 分页
	alarmNotifyRecord := []*AlarmNotifyRecord{}
	alTx.Order(al.CreatedAt.Desc(), al.ID.Desc()).
		Offset(GetPageOffset(page, limit)).
		Limit(GetPageLimit(limit)).
		Scan(&alarmNotifyRecord)
	return alarmNotifyRecord, total, nil
}
